package com.tsfyun.scm.service.impl.order;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Snowflake;
import com.tsfyun.common.base.enums.domain.MaterielStatusEnum;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.scm.dto.materiel.MaterielDTO;
import com.tsfyun.scm.dto.order.ImpOrderMemberSaveDTO;
import com.tsfyun.scm.dto.order.UnboundDetailQTO;
import com.tsfyun.scm.entity.order.ImpOrder;
import com.tsfyun.scm.entity.order.ImpOrderMember;
import com.tsfyun.scm.entity.order.ImpOrderMemberHistory;
import com.tsfyun.scm.entity.order.PriceFluctuationHistory;
import com.tsfyun.scm.mapper.order.ImpOrderMemberMapper;
import com.tsfyun.scm.service.base.ISystemCacheService;
import com.tsfyun.scm.service.materiel.IMaterielService;
import com.tsfyun.scm.service.order.IImpOrderMemberHistoryService;
import com.tsfyun.scm.service.order.IImpOrderMemberService;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.scm.service.order.IOrderMemberReceivingNoService;
import com.tsfyun.scm.system.vo.CustomsCodeVO;
import com.tsfyun.scm.util.TsfWeekendSqls;
import com.tsfyun.scm.vo.materiel.MaterielVO;
import com.tsfyun.scm.vo.order.ImpOrderMemberVO;
import com.tsfyun.scm.vo.order.OrderReceivingBindVO;
import com.tsfyun.scm.vo.order.UnboundDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 订单明细 服务实现类
 * </p>
 *

 * @since 2020-04-08
 */
@Service
public class ImpOrderMemberServiceImpl extends ServiceImpl<ImpOrderMember> implements IImpOrderMemberService {

    @Autowired
    private ImpOrderMemberMapper impOrderMemberMapper;
    @Autowired
    private Snowflake snowflake;
    @Autowired
    private IImpOrderMemberHistoryService impOrderMemberHistoryService;
    @Autowired
    private IMaterielService materielService;
    @Autowired
    private IOrderMemberReceivingNoService orderMemberReceivingNoService;
    @Autowired
    private ISystemCacheService systemCacheService;

    @Override
    public List<ImpOrderMember> getByOrderId(Long impOrderId) {
        TsfWeekendSqls wheres = TsfWeekendSqls.<ImpOrderMember>custom().andEqualTo(false,ImpOrderMember::getImpOrderId,impOrderId);
        List<ImpOrderMember> impOrderMembers = impOrderMemberMapper.selectByExample(Example.builder(ImpOrderMember.class).where(wheres).build());
        if(CollUtil.isNotEmpty(impOrderMembers)){
            //按行号升序
            return impOrderMembers.stream().sorted(Comparator.comparing(ImpOrderMember::getRowNo)).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<ImpOrderMemberVO> findOrderMaterielMember(Long impOrderId) {
        List<ImpOrderMemberVO> list = impOrderMemberMapper.findOrderMaterielMember(impOrderId);
        if(CollUtil.isNotEmpty(list)){
            list.stream().forEach(om ->{
                if(StringUtils.isNotEmpty(om.getHsCode())){
                    CustomsCodeVO customsCodeVO = systemCacheService.getCustomsCodeInfo(om.getHsCode());
                    om.setCsc(customsCodeVO.getCsc());
                    om.setIaqr(customsCodeVO.getIaqr());
                }
            });
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveMembers(ImpOrder impOrder, ImpOrderMemberSaveDTO impOrderMemberSaveDTO, Boolean isSubmit) {
        Integer newSize = 0;//新增物料数
        //删除订单原始明细数据
        impOrderMemberHistoryService.removeByOrderId(impOrder.getId());
        //需要删除的订单明细
        List<ImpOrderMember> deleteOrderMembers = impOrderMemberSaveDTO.getDeleteOrderMembers();
        if(CollUtil.isNotEmpty(deleteOrderMembers)){
            List<Long> orderMemberIds = deleteOrderMembers.stream().map(ImpOrderMember::getId).collect(Collectors.toList());
            List<String> materialIds = deleteOrderMembers.stream().filter(r-> StringUtils.isNotEmpty(r.getMaterialId())).map(ImpOrderMember::getMaterialId).collect(Collectors.toList());
            //删除预绑定入库单数据
            orderMemberReceivingNoService.removeByOrderMemberIds(orderMemberIds);
            //删除明细
            super.removeByIds(orderMemberIds);
            //删除物料
            materielService.removeIdsNotPrompt(materialIds);
        }
        List<ImpOrderMember> impOrderMembers = impOrderMemberSaveDTO.getSaveOrderMembers();
        if(CollUtil.isNotEmpty(impOrderMembers)) {
            for(int i = 0,length = impOrderMembers.size();i < length;i++) {
                impOrderMembers.get(i).setRowNo(i + 1);
                if(Objects.isNull(impOrderMembers.get(i).getId())){
                    impOrderMembers.get(i).setId(snowflake.nextId());
                    impOrderMembers.get(i).setImpOrderId(impOrder.getId());
                }
                impOrderMembers.get(i).setModel(impOrderMembers.get(i).getModel().replace("型号","").replace("型",""));
                impOrderMembers.get(i).setBrand(impOrderMembers.get(i).getBrand().replace("品牌","").replace("牌","").toUpperCase());
                if(isSubmit){
                    MaterielDTO dto = new MaterielDTO();
                    dto.setCustomerId(impOrder.getCustomerId());
                    dto.setModel(impOrderMembers.get(i).getModel());
                    dto.setBrand(impOrderMembers.get(i).getBrand());
                    dto.setName(impOrderMembers.get(i).getName());
                    dto.setSpec(impOrderMembers.get(i).getSpec());
                    dto.setSource("进口订单："+impOrder.getDocNo());
                    dto.setSourceMark(impOrder.getDocNo());
                    MaterielVO materielVO = materielService.obtainMaterialAndSave(dto);
                    if(Objects.equals(MaterielStatusEnum.WAIT_CLASSIFY,MaterielStatusEnum.of(materielVO.getStatusId()))){
                        newSize++;
                    }
                    impOrderMembers.get(i).setMaterialId(materielVO.getId());
                    //物料已归类-同步归类名称
                    if(Objects.equals(MaterielStatusEnum.CLASSED,MaterielStatusEnum.of(materielVO.getStatusId()))){
                        impOrderMembers.get(i).setName(materielVO.getName());
                    }
                }
            }
            impOrderMemberMapper.savaAndUpdateBatch(impOrderMembers);

            //记录原始数据
            List<ImpOrderMemberHistory> historyList = beanMapper.mapAsList(impOrderMembers,ImpOrderMemberHistory.class);
            impOrderMemberHistoryService.savaBatch(historyList);
        }
        return newSize;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveInspectionMembers(ImpOrder impOrder, ImpOrderMemberSaveDTO impOrderMemberSaveDTO) {
        Integer newSize = 0;

        //需要删除的订单明细
        List<ImpOrderMember> deleteOrderMembers = impOrderMemberSaveDTO.getDeleteOrderMembers();
        if(CollUtil.isNotEmpty(deleteOrderMembers)){
            List<Long> orderMemberIds = deleteOrderMembers.stream().map(ImpOrderMember::getId).collect(Collectors.toList());
            orderMemberIds.stream().forEach(mid ->{
                orderMemberReceivingNoService.removeByOrderMemberId(mid);
            });
            List<String> materialIds = deleteOrderMembers.stream().filter(r-> StringUtils.isNotEmpty(r.getMaterialId())).map(ImpOrderMember::getMaterialId).collect(Collectors.toList());
            //删除预绑定入库单数据
            orderMemberReceivingNoService.removeByOrderMemberIds(orderMemberIds);
            //删除明细
            super.removeByIds(orderMemberIds);
            //删除物料
            materielService.removeIdsNotPrompt(materialIds);
        }

        List<ImpOrderMember> impOrderMembers = impOrderMemberSaveDTO.getSaveOrderMembers();
        for(int i = 0,length = impOrderMembers.size();i < length;i++) {
            impOrderMembers.get(i).setRowNo(i + 1);
            MaterielDTO dto = new MaterielDTO();
            dto.setCustomerId(impOrder.getCustomerId());
            dto.setModel(impOrderMembers.get(i).getModel());
            dto.setBrand(impOrderMembers.get(i).getBrand());
            dto.setName(impOrderMembers.get(i).getName());
            dto.setSpec(impOrderMembers.get(i).getSpec());
            dto.setSource("进口订单："+impOrder.getDocNo());
            dto.setSourceMark(impOrder.getDocNo());
            MaterielVO materielVO = materielService.obtainMaterialAndSave(dto);
            if(Objects.equals(MaterielStatusEnum.WAIT_CLASSIFY,MaterielStatusEnum.of(materielVO.getStatusId()))){
                newSize++;
            }
            impOrderMembers.get(i).setMaterialId(materielVO.getId());
            //物料已归类-同步归类名称
            if(Objects.equals(MaterielStatusEnum.CLASSED,MaterielStatusEnum.of(materielVO.getStatusId()))){
                impOrderMembers.get(i).setName(materielVO.getName());
            }
            if(Objects.isNull(impOrderMembers.get(i).getId())){
                impOrderMembers.get(i).setId(snowflake.nextId());
                impOrderMembers.get(i).setImpOrderId(impOrder.getId());
            }
        }
        impOrderMemberMapper.savaAndUpdateBatch(impOrderMembers);
        return newSize;
    }

    @Override
    public List<PriceFluctuationHistory> findImpHistory(LocalDateTime dateTime, String model) {
        return impOrderMemberMapper.findImpHistory(dateTime,model);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateMateriel(List<ImpOrderMember> impOrderMemberList) {
        impOrderMemberMapper.batchUpdateMateriel(impOrderMemberList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMemberMaterielId(String oldId, String newId) {
        impOrderMemberMapper.updateMemberMaterielId(oldId,newId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdatePartData(List<ImpOrderMember> impOrderMemberList) {
        impOrderMemberList.stream().forEach(iom->{
            updateByIdSelective(iom);
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateSplitMembers(List<ImpOrderMember> impOrderMemberList) {
        if(CollUtil.isNotEmpty(impOrderMemberList)){
            impOrderMemberMapper.batchUpdateSplitMembers(impOrderMemberList);
        }
    }

    @Override
    public List<UnboundDetailVO> unboundDetailList(UnboundDetailQTO qto) {
        return impOrderMemberMapper.unboundDetailList(qto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeByImpOrderId(Long orderId) {
        impOrderMemberMapper.deleteByExample(Example.builder(ImpOrderMember.class).where(TsfWeekendSqls.<ImpOrderMember>custom().andEqualTo(false,ImpOrderMember::getImpOrderId,orderId)).build());
    }

}
